package com.dongnao.jack.registry.handler;

import java.util.List;
import java.util.Map;

import org.springframework.context.ApplicationContext;

import com.dongnao.jack.spring.parse.ReferenceConfig;
import com.dongnao.jack.spring.parse.RegistryConfig;
import com.dongnao.jack.spring.parse.ServiceConfig;

/**
 * 
 * @ClassName: RegistryDelegate 
 * @Description: 责任分发serice注册方式 
 * @author xuyp
 * @date 2018年4月20日 下午2:17:52 
 *
 */
public class RegistryDelegate {

    /**
     * 
     * @Title: registryService 
     * @Description: 分发service的注册方式并完成注册
     * @param service
     * @return TODO(说明)
     * @throws 
     * @author xuyp
     * @date 2018年4月20日 下午2:18:20
     */
    public static boolean registryService(ServiceConfig service) {

        if (service != null) {

            ApplicationContext context = service.getApplicationContext();

            Map<String, RegistryConfig> map = context.getBeansOfType(RegistryConfig.class);
            RegistryConfig config = map.values().iterator().next();
            if (map.containsKey(service.getProtocol())) {
                config = map.get(service.getProtocol());
            }

            return config.getServiceMap().get(service.getProtocol()).serviceregistry(service.getRef(),
                    service.getInterfaceClass(), context);
        }

        return false;
    }

    public static List<String> getRegistry(ReferenceConfig config) {

        ApplicationContext applicationContext = config.getApplicationContext();
        Map<String, RegistryConfig> registryMap = applicationContext.getBeansOfType(RegistryConfig.class);
        RegistryConfig registryConfig = null;
        for (String key : registryMap.keySet()) {
            if (key.equals(config.getProtocol())) {
                registryConfig = registryMap.get(key);
            }
        }

        if (registryConfig == null) {
            registryConfig = registryMap.values().iterator().next();
        }

        return registryConfig.getServiceMap().get(config.getProtocol()).getRegistry(config.getInterfaceClass(),
                config.getApplicationContext());
    }

}
